﻿using Identity.API.Data;
using Identity.API.Models;
using Microsoft.EntityFrameworkCore;
using RepositoryLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Identity.API.Services
{
    public class LoginUserRepository: ILoginUserRepository
    {
        private readonly ApplicationDbContext _context;
        public IUnitOfWork UnitOfWork
        {
            get
            {
                return _context;
            }
        }

        public LoginUserRepository(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public WeChatLoginUser Add(WeChatLoginUser loginUser)
        {
            if (!_context.WeChatLoginUsers.Any(t => t.OpenId == loginUser.OpenId))
            {
                return _context.WeChatLoginUsers
                    .Add(loginUser)
                    .Entity;
            }
            else
            {
                return loginUser;
            }
        }

        public WeChatLoginUser Update(WeChatLoginUser loginUser)
        {
            return _context.WeChatLoginUsers
                    .Update(loginUser)
                    .Entity;
        }

        public async Task<WeChatLoginUser> FindByIdAsync(string id)
        {
            var loginUser = await _context.WeChatLoginUsers
                .Where(b => b.OpenId == id)
                .SingleOrDefaultAsync();
            return loginUser;
        }
    }
}
